package com.gao.d_selector.d;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author gao
 * @time 2020/08/11 19:09:37
 */
public class TimeClient {

    private Selector selector;
    private SocketChannel channel;
    private Scanner sc;

    public TimeClient() throws IOException {
        selector = Selector.open();
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        sc = new Scanner(System.in);
    }

    public void start() {
        try {
            channel.connect(new InetSocketAddress("127.0.0.1", 8888));
            channel.register(selector, SelectionKey.OP_CONNECT);

            while (true) {
                int n = selector.select();
                if (n > 0) {
                    Set<SelectionKey> selectedKeys = selector.selectedKeys();
                    Iterator<SelectionKey> it = selectedKeys.iterator();
                    while (it.hasNext()) {
                        SelectionKey key = it.next();
                        it.remove();
                        if (key.isValid() && key.isConnectable()) {
                            connect(key);
                        }
                        if (key.isValid() && key.isWritable()) {
                            write(key);
                        }
                        if (key.isValid() && key.isReadable()) {
                            read(key);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void read(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(100);
            // write to buffer
            channel.read(buffer);
            // write mode to read mode
            buffer.flip();
            byte[] readBytes = new byte[buffer.limit()];
            // read from buffer to readBytes
            buffer.get(readBytes);
            String msg = new String(readBytes);
            System.out.println("read msg from server: " + msg);
            key.interestOps(SelectionKey.OP_WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void write(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            System.out.println("Enter the msg to send to the server， if the msg is 'what's the time?'，the server will response！");
            String msg = sc.nextLine();
            ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
            channel.write(byteBuffer);
            if ("what's the time?".equalsIgnoreCase(msg)) {
                key.interestOps(SelectionKey.OP_READ);
            }
            if ("exit".equalsIgnoreCase(msg)) {
                key.cancel();
                channel.close();
                System.exit(0);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void connect(SelectionKey key) {
        try {
            SocketChannel channel = (SocketChannel) key.channel();
            channel.finishConnect();
            System.out.println("connected to the server...");
            channel.configureBlocking(false);
            channel.register(selector, SelectionKey.OP_WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        TimeClient timeClient = new TimeClient();
        timeClient.start();

    }
}
